package cn.com.v2.controller;

import cn.com.v2.common.base.BaseController;
import cn.com.v2.common.domain.AjaxResult;
import cn.com.v2.model.*;
import cn.com.v2.model.dto.PutOnResourceMarketDTO;
import cn.com.v2.model.query.ResourceMarketQuery;
import cn.com.v2.model.vo.EvVO;
import cn.com.v2.model.vo.ResourceProjectVo;
import cn.com.v2.service.*;
import cn.com.v2.util.SaTokenUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 罗添煦
 * @description
 * @create 2025-05-20 下午12:27
 */
@RestController
@RequestMapping("/api/resourceMarket")
public class ResourceMarketController extends BaseController {

    @Resource
    private IResourceMarketService resourceMarketService;
    @Resource
    private IResourceTypeService resourceTypeService;
    @Resource
    private IProjectService projectService;
    @Resource
    private IUserResourceTemplateService userResourceTemplateService;
    @Resource
    private IProjectDataService projectDataService;
    @Resource
    private ISysUserService userService;

    // 获取资源市场分类名称
    @GetMapping("/getResourceTypeList")
    public AjaxResult getResourceType() {
        List<ResourceType> resourceTypes = resourceTypeService.list();
        List<EvVO> resourceTypeList = resourceTypes.stream().map(resourceType -> {
            return EvVO.builder().id(resourceType.getId()).typeName(resourceType.getTypeName()).build();
        }).collect(Collectors.toList());
        return retobject(200, resourceTypeList);
    }

    // 添加资源市场分类
    @PostMapping("/addResourceType")
    public AjaxResult addResourceType(@RequestBody ResourceType resourceType) {
        boolean save = resourceTypeService.save(resourceType);
        if (save) {
            return success();
        }
        return error();
    }

    // 修改资源市场分类
    @PostMapping("/updateResourceType")
    public AjaxResult updateResourceType(@RequestBody ResourceType resourceType) {
        boolean update = resourceTypeService.updateById(resourceType);
        if (update) {
            return success();
        }
        return error();
    }

    // 删除资源市场分类
    @PostMapping("/deleteResourceType")
    public AjaxResult deleteResourceType(@RequestBody ResourceType resourceType) {
        boolean delete = resourceTypeService.removeById(resourceType.getId());
        if (delete) {
            return success();
        }
        return error();
    }

    // 分页获取资源市场资源，根据分类进行获取
    @PostMapping("/getResourceListByType")
    public AjaxResult getResourceListByType(@RequestBody ResourceMarketQuery query) {
        IPage<ResourceMarket> page = new Page<>();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());
        LambdaQueryWrapper<ResourceMarket> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(query.getResourceMarketName())) {
            wrapper.like(ResourceMarket::getResourceName, query.getResourceMarketName());
        }
        if (StringUtils.isNotBlank(query.getResourceTypeId())) {
            page = resourceMarketService.page(page, wrapper.eq(ResourceMarket::getResourceTypeId, query.getResourceTypeId()));
        } else {
            page = resourceMarketService.page(page, wrapper);
        }
        List<ResourceMarket> records = page.getRecords();
        if (records.isEmpty()) {
            return AjaxResult.successData(200, null);
        }
        ArrayList<ResourceProjectVo> resourceProjectVos = new ArrayList<>();
        for (ResourceMarket record : records) {
            LambdaQueryWrapper<Project> projectLambdaQueryWrapper = new LambdaQueryWrapper<>();
            projectLambdaQueryWrapper.in(Project::getId, record.getProjectId());
            Project project = projectService.getOne(projectLambdaQueryWrapper);
            ResourceProjectVo resourceProjectVo = new ResourceProjectVo();
            BeanUtils.copyProperties(project, resourceProjectVo);
            resourceProjectVo.setProjectName(record.getResourceName());
            LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sysUserLambdaQueryWrapper.eq(SysUser::getId, record.getCreateUserId());
            SysUser user = userService.getOne(sysUserLambdaQueryWrapper);
            resourceProjectVo.setUserName(user.getUsername());
            resourceProjectVo.setUserUri("https://img0.baidu.com/it/u=2317612037,2363737113&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500");
            resourceProjectVos.add(resourceProjectVo);
        }
        return successData(200, resourceProjectVos);
    }

    // 上下架资源市场资源
    @PostMapping("/putOnResourceMarket")
    public AjaxResult putOnResourceMarket(@RequestBody PutOnResourceMarketDTO putOnResourceMarketDTO) {
        if (putOnResourceMarketDTO.getIsPublish()) {
            LambdaQueryWrapper<ResourceMarket> projectLambdaQueryWrapper = new LambdaQueryWrapper<>();
            projectLambdaQueryWrapper.eq(ResourceMarket::getProjectId, putOnResourceMarketDTO.getProjectId());
            ResourceMarket resourceMarket = resourceMarketService.getOne(projectLambdaQueryWrapper);
            if (resourceMarket != null) {
                resourceMarket.setIfDelete(0);
                resourceMarketService.updateById(resourceMarket);
            } else {
                resourceMarket = new ResourceMarket();
                resourceMarket.setResourceName(putOnResourceMarketDTO.getResourceName());
                resourceMarket.setResourceDesc(putOnResourceMarketDTO.getResourceDesc());
                resourceMarket.setResourceTypeId(Integer.parseInt(putOnResourceMarketDTO.getResourceTypeId()));
                resourceMarket.setProjectId(putOnResourceMarketDTO.getProjectId());
                String userId = SaTokenUtil.getUserId();
                resourceMarket.setCreateUserId(userId);
                resourceMarket.setIfDelete(0);
                resourceMarketService.save(resourceMarket);
            }
            LambdaUpdateWrapper<Project> projectLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            projectLambdaUpdateWrapper.eq(Project::getId, putOnResourceMarketDTO.getProjectId());
            projectLambdaUpdateWrapper.set(Project::getIfPublish, 1);
            projectService.update(projectLambdaUpdateWrapper);
            return success();
        } else {
            LambdaUpdateWrapper<Project> projectLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            projectLambdaUpdateWrapper.eq(Project::getId, putOnResourceMarketDTO.getProjectId());
            projectLambdaUpdateWrapper.set(Project::getIfPublish, 0);
            projectService.update(projectLambdaUpdateWrapper);
            LambdaUpdateWrapper<ResourceMarket> resourceMarketLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            resourceMarketLambdaUpdateWrapper.eq(ResourceMarket::getProjectId, putOnResourceMarketDTO.getProjectId());
            resourceMarketLambdaUpdateWrapper.set(ResourceMarket::getIfDelete, 1);
            resourceMarketService.update(resourceMarketLambdaUpdateWrapper);
            return success();
        }
    }

    // 添加到自己使用模板
    @GetMapping("/addToUserResource")
    public AjaxResult addToUserResource(@RequestParam("projectId") String projectId) {
        String userId = SaTokenUtil.getUserId();
        UserResourceTemplate userResourceTemplate = new UserResourceTemplate();
        userResourceTemplate.setProjectId(projectId);
        userResourceTemplate.setCreateUserId(userId);
        userResourceTemplate.setIsUse(0);
        userResourceTemplateService.save(userResourceTemplate);
        return success();
    }

    // 直接使用模板
    @GetMapping("/useResourceTemplate")
    public AjaxResult useResourceTemplate(@RequestParam("projectId") String projectId) {
        // 保存到我的模板中
        String userId = SaTokenUtil.getUserId();
        UserResourceTemplate userResourceTemplate = new UserResourceTemplate();
        userResourceTemplate.setProjectId(projectId);
        userResourceTemplate.setCreateUserId(userId);
        userResourceTemplate.setIsUse(1);
        userResourceTemplateService.save(userResourceTemplate);
        // 查询项目信息
        LambdaQueryWrapper<Project> projectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        projectLambdaQueryWrapper.eq(Project::getId, projectId);
        Project project = projectService.getOne(projectLambdaQueryWrapper);
        project.setId(null);
        project.setCreateUserId(userId);
        project.setIfPublish(0);
        projectService.save(project);
        // 设置项目数据
        LambdaQueryWrapper<ProjectData> projectDataLambdaQueryWrapper = new LambdaQueryWrapper<>();
        projectDataLambdaQueryWrapper.eq(ProjectData::getProjectId, projectId);
        ProjectData projectData = projectDataService.getOne(projectDataLambdaQueryWrapper);
        projectData.setId(null);
        projectData.setProjectId(project.getId());
        projectDataService.save(projectData);
        return success(project.getId());
    }

    // 使用自己的模板
    @GetMapping("/useMyResourceTemplate")
    public AjaxResult useMyResourceTemplate(@RequestParam("projectId") String projectId) {
        // 保存到我的模板中
        String userId = SaTokenUtil.getUserId();
        LambdaUpdateWrapper<UserResourceTemplate> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(UserResourceTemplate::getProjectId, projectId);
        wrapper.eq(UserResourceTemplate::getCreateUserId, userId);
        wrapper.set(UserResourceTemplate::getIsUse, 1);
        userResourceTemplateService.update(wrapper);
        // 查询项目信息
        LambdaQueryWrapper<Project> projectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        projectLambdaQueryWrapper.eq(Project::getId, projectId);
        Project project = projectService.getOne(projectLambdaQueryWrapper);
        project.setId(null);
        project.setCreateUserId(userId);
        project.setIfPublish(0);
        projectService.save(project);
        // 设置项目数据
        LambdaQueryWrapper<ProjectData> projectDataLambdaQueryWrapper = new LambdaQueryWrapper<>();
        projectDataLambdaQueryWrapper.eq(ProjectData::getProjectId, projectId);
        ProjectData projectData = projectDataService.getOne(projectDataLambdaQueryWrapper);
        projectData.setId(null);
        projectData.setProjectId(project.getId());
        projectDataService.save(projectData);
        return success(project.getId());
    }

    // 删除自己使用模板
    @GetMapping("/deleteUserResource")
    public AjaxResult deleteUserResource(@RequestParam("projectId") String projectId) {
        String userId = SaTokenUtil.getUserId();
        userResourceTemplateService.remove(new LambdaQueryWrapper<UserResourceTemplate>()
                .eq(UserResourceTemplate::getProjectId, projectId)
                .eq(UserResourceTemplate::getCreateUserId, userId));
        return success();
    }

    // 获取自己使用模板
    @PostMapping("/getMyResourceTemplate")
    public AjaxResult getMyResourceTemplate(@RequestBody ResourceMarketQuery query) {
        String userId = SaTokenUtil.getUserId();
        ArrayList<ResourceProjectVo> resourceProjectVos = new ArrayList<>();
        IPage<UserResourceTemplate> userResourceTemplatePage = new Page<>();
        userResourceTemplatePage.setCurrent(query.getPageNum());
        userResourceTemplatePage.setSize(query.getPageSize());

        LambdaQueryWrapper<UserResourceTemplate> wrapper = new LambdaQueryWrapper<UserResourceTemplate>()
        .eq(UserResourceTemplate::getCreateUserId, userId)
        .eq(UserResourceTemplate::getIsUse, 0);
        userResourceTemplatePage = userResourceTemplateService.page(userResourceTemplatePage, wrapper);
        List<UserResourceTemplate> list = userResourceTemplatePage.getRecords();
        List<String> projectList = list.stream().map(UserResourceTemplate::getProjectId).collect(Collectors.toList());
        if(projectList.isEmpty()){
            return successData(200, null);
        }
        LambdaQueryWrapper<Project> projectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        projectLambdaQueryWrapper.in(Project::getId, projectList);
        List<Project> projects = projectService.list(projectLambdaQueryWrapper);
        projects.forEach(project -> {
            ResourceProjectVo resourceProjectVo = new ResourceProjectVo();
            BeanUtils.copyProperties(project, resourceProjectVo);
            LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sysUserLambdaQueryWrapper.eq(SysUser::getId, project.getCreateUserId());
            SysUser user = userService.getOne(sysUserLambdaQueryWrapper);
            resourceProjectVo.setUserName(user.getUsername());
            resourceProjectVo.setUserUri("https://img0.baidu.com/it/u=2317612037,2363737113&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500");
            resourceProjectVos.add(resourceProjectVo);
        });
        return successData(200,resourceProjectVos);
    }
}
